﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using AllenHung.FeedReader.Resources;
using Windows.Phone.Speech.VoiceCommands;
using System.IO;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
using Windows.Phone.Speech.Synthesis;
using Windows.Phone.Speech.Recognition;
using Windows.Foundation;
using System.ComponentModel;
using System.Threading;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace AllenHung.FeedReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        private int tickCount = 0;
        private bool voiceCommandInitialized = false;
        private RoutedEventHandler onLoadedEventHandler;
        private DispatcherTimer speechTimer;
        internal SpeechSynthesizer synthesizer;                             // The speech synthesizer (text-to-speech, TTS) object
        internal SpeechRecognizer recognizer;                               // The speech recognition object
        private bool recognizeInProgress = false;
        private int skipCounter = 0;
        //  internal  SpeechRecognitionResult recoOperation;    // Used to canel the current asynchronous speech recognition operation

        private BackgroundWorker databaseWorker;
        private static bool IsDataLoaded = false;
        private Dictionary<string, Action> ActionMap = null;

        internal static ObservableCollection<FeedSource> AllFeedSources, SubscribedFeedSources;
        private static int CurrentIndex = -1;
        private static bool ExecutingCommand = false;

        private static string[] MainPageVocabulary = new string[]{
            "next",
            "previous",
            "select"
        };

        //  internal static bool RecoEnabled = true;                // When this is true, we will continue to recognize 
        private static MainModel _Model = null;
        internal static MainModel MainModel
        {
            get
            {
                // Delay creation of the view model until necessary
                if (_Model == null)
                    _Model = new MainModel("isostore:/AudioFeed.sdf");

                return _Model;
            }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            this.onLoadedEventHandler = new RoutedEventHandler(OnLoaded);
            this.Loaded += onLoadedEventHandler;
            // Create the speech recognizer and speech synthesizer objects. 
            synthesizer = new SpeechSynthesizer();
            recognizer = new SpeechRecognizer();
            //    recognizer.Settings.BabbleTimeout = new TimeSpan(4 * TimeSpan.TicksPerSecond);
            //    recognizer.Settings.InitialSilenceTimeout = new TimeSpan(4 * TimeSpan.TicksPerSecond);
            // Attach event handlers.
            recognizer.Grammars.AddGrammarFromList("MainPage", MainPageVocabulary);

            ActionMap = new Dictionary<string, Action>();
            ActionMap.Add(MainPageVocabulary[0], this.NextFeedSrc);
            ActionMap.Add(MainPageVocabulary[1], this.PreviousFeedSrc);
            ActionMap.Add(MainPageVocabulary[2], this.SelectFeedSrc);
        }



        // This method determines whether the user has navigated to the application after the application was tombstoned.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //if (recoOperation != null && recoOperation.Status == AsyncStatus.Started)
            //{
            //    recoOperation.Cancel();
            //    recoOperation.Close();
            //}
            //if (recognizer != null)
            //{
            //    recognizer.Dispose();
            //}
            base.OnNavigatedTo(e);
            Debug.WriteLine("On NavigatedTo MainPage");
            App.CurrentPage = 1;
            //}
            //if (recognizer == null)
            //{

            // Set up a list of colors to recognize.
            //}
            if (!App.SpeechOn)
            {
                BitmapImage muteImage = new BitmapImage(new Uri("/Assets/mute.png", UriKind.Relative));
                SpeechButtonImage.Source = muteImage;
                SpeechStatusText.Background = (Brush)Application.Current.Resources["DisabledBrush"];
                SpeechStatusText.BorderBrush = (Brush)Application.Current.Resources["DisabledBrush"];
                SpeechStatusText.Content = "Disabled";
            }
            else
            {
                CurrentIndex = -1;
                speechTimer = new System.Windows.Threading.DispatcherTimer();
                speechTimer.Tick += new EventHandler(speechTimer_Tick);
                speechTimer.Interval = new TimeSpan(500 * TimeSpan.TicksPerMillisecond);
                speechTimer.Start();
                BitmapImage muteImage = new BitmapImage(new Uri("/Assets/microphone.png", UriKind.Relative));
                SpeechButtonImage.Source = muteImage;
                SpeechStatusText.Background = (Brush)Application.Current.Resources["FeedBrush"];
                SpeechStatusText.BorderBrush = (Brush)Application.Current.Resources["FeedBrush"];
                SpeechStatusText.Content = "Listening ...";
                Deployment.Current.Dispatcher.BeginInvoke(async () =>
                {
                    await synthesizer.SpeakTextAsync("Welcome to Feed Reader. Say \"next\" to focus on a feed");
                });
            }
            if (!IsDataLoaded)
            {
                databaseWorker = new BackgroundWorker();
                databaseWorker.DoWork += new DoWorkEventHandler(backroungWorker_LoadDatabase);
                databaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backroungWorker_RunWorkerCompleted);
                databaseWorker.RunWorkerAsync();
            }
            else
            {
                ContentPanel.ItemsSource = SubscribedFeedSources;
            }
        }



        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //Stop listening when navigate away
            base.OnNavigatedFrom(e);
            // Cancel the outstanding recognition operation, if one exists
            // if (recoOperation != null && recoOperation.Status == AsyncStatus.Started)
            // {
            //     recoOperation.Cancel();
            ////     recoOperation.Close();
            // }
            // if (recognizer != null)
            // {
            //     recognizer.Dispose();
            // }
            // if (synthesizer != null)
            // {
            //     synthesizer.Dispose();
            Debug.WriteLine("OnNavigatedFrom MainPage");
            App.CurrentPage = 0;
 
            // }
            if (App.SpeechOn)
            {
                speechTimer.Stop();
            }
        }

        private async void speechTimer_Tick(object sender, EventArgs e)
        {
            tickCount = (tickCount + 1) % 10000;
            int curTick = tickCount;
            if (!recognizeInProgress)
            {
                Debug.WriteLine(curTick + " Start recognizing");
                skipCounter = 0;
                recognizeInProgress = true;
                //CurrentRecogTick = curTick;
                try
                {// Start recognition.
                    SpeechRecognitionResult recoResult = await recognizer.RecognizeAsync();
                    //if (MainPage.CurrentRecogTick != curTick)
                    //{
                    //    
                    //    return;
                    //}
                    if (App.CurrentPage != 1)
                    {
                        Debug.WriteLine(curTick + " party over page navigated away");
                        return;
                    }
                    // Check to see if speech input was rejected and prompt the user.
                    if (recoResult.TextConfidence == SpeechRecognitionConfidence.Rejected)
                    {
                        // SetSpeechStatusText("Sorry, didn't catch that");
                        Debug.WriteLine(curTick + " Rejected silence");
                    }

                    // Check to see if speech input was recognized with low confidence and prompt the user to speak again.
                    else if (recoResult.TextConfidence == SpeechRecognitionConfidence.Low ||
                        recoResult.TextConfidence == SpeechRecognitionConfidence.Medium)
                    {
                        if (ExecutingCommand)
                        {
                            Debug.WriteLine(curTick + " low confidence someone already take care of this");
                        }
                        else
                        {
                            ExecutingCommand = true;
                            Debug.WriteLine(curTick + " Sorry I didn't get that");
                            SetSpeechStatusText("Sorry I didn't get that");
                            await synthesizer.SpeakTextAsync("Sorry I didn't get that");
                            BackgroundWorker backgroundWorker = new BackgroundWorker();
                            backgroundWorker.DoWork += new DoWorkEventHandler(ResetExecutingCommandStatus1sec);
                            backgroundWorker.RunWorkerAsync();
                        }
                    }

                    // Check to see if speech input was recognized and confirm the result.
                    else if (recoResult.TextConfidence == SpeechRecognitionConfidence.High)
                    {
                        if (ExecutingCommand)
                        {
                            Debug.WriteLine(curTick + " someone already take care of this");
                        }
                        else
                        {
                            Debug.WriteLine(curTick + " You say " + recoResult.Text);
                            SetSpeechStatusText("You say " + recoResult.Text);
                            if (ActionMap.ContainsKey(recoResult.Text))
                            {
                                ExecutingCommand = true;
                                Action act = ActionMap[recoResult.Text];
                                act();
                                BackgroundWorker backgroundWorker = new BackgroundWorker();
                                backgroundWorker.DoWork += new DoWorkEventHandler(ResetExecutingCommandStatus);
                                backgroundWorker.RunWorkerAsync();
                            }
                            else
                            {
                                await synthesizer.SpeakTextAsync(recoResult.Text + " is an unknown command. Say \"next\", \"previous\", or \"select\"");
                            }
                        }
                    }
                    //else if 
                    //{

                    //}
                    recognizeInProgress = false;
                    Debug.WriteLine(curTick + " Recognizing done");
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(curTick + " HRESULT: " + exc.HResult + " " + exc.StackTrace);
                    Debug.WriteLine(curTick + " HRESULT: " + exc.HResult + " " + exc.Message);
                }
            }
            else
            {
                if (++skipCounter == 10)
                {
                    Debug.WriteLine(curTick + " Stale recognizer");
                    // recognizer.Dispose();
                    recognizer = new SpeechRecognizer();
                    //    recognizer.Settings.BabbleTimeout = new TimeSpan(4 * TimeSpan.TicksPerSecond);
                    //   recognizer.Settings.InitialSilenceTimeout = new TimeSpan(4 * TimeSpan.TicksPerSecond);
                    // Attach event handlers.
                    recognizer.Grammars.AddGrammarFromList("MainPage", MainPageVocabulary);
                    recognizeInProgress = false;
                }
                Debug.WriteLine(curTick + " Skip recognizing");
            }
        }




        // Register the voice commands. Called when the app is first launched.  
        public async void OnLoaded(object sender, EventArgs e)
        {
            if (!this.voiceCommandInitialized)
            {
                try
                {
                    Uri uri = new Uri("ms-appx:///ReaderVoiceCommand.xml", UriKind.Absolute);
                    await VoiceCommandService.InstallCommandSetsFromFileAsync(uri);
                    voiceCommandInitialized = true;
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message + "\r\nVoice Commands failed to initialize.");
                    throw error;
                }
            }
            //if (App.SpeechOn)
            //{
            //    // Continuously recognize speech until the user has canceled 
            //    while (RecoEnabled)
            //    {
            //        try
            //        {
            //            // Perform speech recognition.  
            //            recoOperation = recognizer.RecognizeAsync();
            //            var recoResult = await recoOperation;

            //            // Check the confidence level of the speech recognition attempt.
            //            if (recoResult.TextConfidence < SpeechRecognitionConfidence.Medium)
            //            {
            //                // If the confidence level of the speech recognition attempt is low, 
            //                // ask the user to try again.
            //                SetSpeechStatusText("Not sure what you said...");

            //                //  await synthesizer.SpeakTextAsync("Not sure what you said, please try again");
            //            }
            //            else
            //            {
            //                // Output that the color of the rectangle is changing by updating
            //                // the TextBox control and by using text-to-speech (TTS). 
            //                SetSpeechStatusText("You said: " + recoResult.Text);
            //                await synthesizer.SpeakTextAsync("select the " + recoResult.Text + " item");

            //                // Set the fill color of the rectangle to the recognized color. 
            //                //    rectangleResult.Background = TryGetBrush(recoResult.Text.ToLower());

            //            }
            //        }
            //        catch (System.Threading.Tasks.TaskCanceledException)
            //        {
            //            // Ignore the cancellation exception of the recoOperation.
            //            // When recoOperation.Cancel() is called to cancel the asynchronous speech recognition operation
            //            // initiated by RecognizeAsync(),  a TaskCanceledException is thrown to signify early exit.
            //        }
            //        catch (Exception err)
            //        {
            //            // Handle the speech privacy policy error.
            //            const int privacyPolicyHResult = unchecked((int)0x80045509);

            //            if (err.HResult == privacyPolicyHResult)
            //            {
            //                MessageBox.Show("To run this app, you must first accept the speech privacy policy. To do so, navigate to Settings -> speech on your phone and check 'Enable Speech Recognition Service' ");
            //                RecoEnabled = false;
            //                // btnContinuousRecognition.Content = "Start speech recognition";
            //            }
            //            else
            //            {
            //                //  txtResult.Text = "Error: " + err.Message;
            //            }
            //        }
            //    }
            //}
        }


        private void AddFeed_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/FeedPickerPage.xaml", UriKind.Relative));
        }

        private void Feed1_Click(object sender, EventArgs e)
        {
            //if (recoOperation != null && recoOperation.Status == AsyncStatus.Started)
            //{
            //    recoOperation.Cancel();
            //}

            NavigationService.Navigate(new Uri("/ArticleListPage.xaml", UriKind.Relative));
        }

        private void DeleteFeed_Click(object sender, EventArgs e)
        {
        }

        private void Settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }

        private void About_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        private void SetSpeechStatusText(string value)
        {
            SpeechStatusText.Content = value;
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(DelayResetSpeechStatusText);
            backgroundWorker.RunWorkerAsync();
        }

        private void DelayResetSpeechStatusText(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(8000);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                SpeechStatusText.Content = AppResources.listening;
            }
            );
        }

        private void ResetExecutingCommandStatus(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);
            ExecutingCommand = false;
            Debug.WriteLine("Reset ExecutingCommandStatus");
        }

        private void ResetExecutingCommandStatus1sec(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1200);
            ExecutingCommand = false;
            Debug.WriteLine("Reset ExecutingCommandStatus 1sec");
        }

        internal static void LoadSettings()
        {
            object[] savedValues = MainModel.LoadFromIsolatedStorage();
            App.SpeechOn = (bool)savedValues[0];
            App.AutoplayNext = (bool)savedValues[1];
        }

        internal static void SaveToIsolatedStorage()
        {
            object[] savedValues = new object[MainModel.MAX_OPTION];
            savedValues[0] = App.SpeechOn;
            savedValues[1] = App.AutoplayNext;
            MainModel.SaveToIsolatedStorage(savedValues);
        }

        // Handle selection changed on ListBox
        private void FeedList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            Debug.WriteLine("feedlist selection change " + ContentPanel.SelectedIndex);
            // If selected index is -1 (no selection) do nothing
            //if (ContentPanel.SelectedIndex == -1)
            //    return;
            //else
            //{
            //    FeedSource src = (FeedSource)ContentPanel.SelectedItem;
            //    NavigationService.Navigate(new Uri("/ArticleListPage.xaml?" + ArticleListPage.UriKey + "=" + src.SourceUri, UriKind.Relative));
            //}
            //ContentPanel.SelectedIndex = -1;
        }

        private void backroungWorker_LoadDatabase(object sender, DoWorkEventArgs e)
        {
            if (!MainModel.DatabaseExists())
            {
                MainModel.CreateDatabase();
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "CNN",
                    IsSubscribed = true,
                    SourceImagePath = "/Assets/cnnicon.png",
                    SourceUri = "http://rss.cnn.com/rss/cnn_topstories.rss"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "BBC News",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/bbcicon.png",
                    SourceUri = "http://feeds.bbci.co.uk/news/world/rss.xml"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "ESPN",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/espnicon.png",
                    //SourceUri = "http://sports.espn.go.com/espn/rss/news"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "Engadget",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/engadget.jpg",
                    SourceUri = "http://www.engadget.com/rss.xml"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "Cnet News",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/cnetnews.jpg",
                    SourceUri = "http://feeds.feedburner.com/cnet/tcoc?format=xml"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "New York Times",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/nytimesicon.png",
                    SourceUri = "http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml"
                });
                MainModel.FeedSources.InsertOnSubmit(new FeedSource
                {
                    SourceName = "Reuters",
                    IsSubscribed = false,
                    SourceImagePath = "/Assets/reutersicon.png",
                    SourceUri = "http://feeds.reuters.com/reuters/topNews?format=xml"
                });
                MainModel.SubmitChanges();
            }
            var sourcesInDB = from FeedSource sources in MainModel.FeedSources
                              select sources;
            AllFeedSources = new ObservableCollection<FeedSource>(sourcesInDB);
            SubscribedFeedSources = new ObservableCollection<FeedSource>();
            foreach (FeedSource src in AllFeedSources)
            {
                if (src.IsSubscribed)
                {
                    SubscribedFeedSources.Add(src);
                }
            }

        }

        private void backroungWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                ContentPanel.ItemsSource = SubscribedFeedSources;
                //ContentPanel.Items.fir
            });
            IsDataLoaded = true;
        }


        private void SrcButtonClick(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("feedlist selection change button " + ContentPanel.SelectedIndex);
            Button b = sender as Button;
            FeedSource src = b.DataContext as FeedSource;
            App.currentFeedURI = src.SourceUri;
            NavigationService.Navigate(new Uri("/ArticleListPage.xaml?" + ArticleListPage.UriKey + "=" + src.SourceUri, UriKind.Relative));
        }

        private async void NextFeedSrc()
        {
            String newCur = null;
            if (CurrentIndex < 0 || CurrentIndex > SubscribedFeedSources.Count - 1)
            {
                CurrentIndex = 0;
            }
            else
            {
                UnfocusCurrentItem();
                CurrentIndex = (CurrentIndex + 1) % SubscribedFeedSources.Count;
                Debug.WriteLine("NextFeedSrc current index " + CurrentIndex);
            }
            newCur = FocusCurrentItem();
            String nextCur = GetNextFeedName();
            await synthesizer.SpeakTextAsync("Move to next item in list. Focus on " + newCur + ". Adjacent item is " + nextCur);
        }

        private async void PreviousFeedSrc()
        {
            String newCur = null;
            if (CurrentIndex < 0 || CurrentIndex > SubscribedFeedSources.Count - 1)
            {
                CurrentIndex = SubscribedFeedSources.Count - 1;
            }
            else
            {
                UnfocusCurrentItem();
                CurrentIndex = (CurrentIndex - 1 + SubscribedFeedSources.Count) % SubscribedFeedSources.Count;
                Debug.WriteLine("PreviousFeedSrc current index " + CurrentIndex);
            }
            newCur = FocusCurrentItem();
            String prevCur = GetPreviousFeedName();
            await synthesizer.SpeakTextAsync("Move to previous item in list. Focus on " + newCur + ". Adjacent item is " + prevCur);
        }

        private async void SelectFeedSrc()
        {
            if (CurrentIndex < 0 || CurrentIndex > SubscribedFeedSources.Count - 1)
            {
                await synthesizer.SpeakTextAsync("No item focused. Say \"Next\" to select a feed subscription");
            }
            else
            {
                Debug.WriteLine("current index = " + CurrentIndex);
                ListBoxItem item = ContentPanel.ItemContainerGenerator.ContainerFromIndex(CurrentIndex) as ListBoxItem;
                Button itemButton = App.FindFirstElementInVisualTree<Button>(item);
                TextBlock bttnText = App.FindFirstElementInVisualTree<TextBlock>(itemButton);
                await synthesizer.SpeakTextAsync("Navigate to feed subscription " + bttnText.Text);
                this.SrcButtonClick(itemButton, null);
            }
        }

        private void UnfocusCurrentItem()
        {
            //ListBoxItem item = ContentPanel.Items[CurrentIndex] as ListBoxItem;
            //Button itemButton = item.FindName("SrcButton") as Button;
            Debug.WriteLine("unfocus current index = " + CurrentIndex);
            ListBoxItem item = ContentPanel.ItemContainerGenerator.ContainerFromIndex(CurrentIndex) as ListBoxItem;
            Button itemButton = App.FindFirstElementInVisualTree<Button>(item);
            //   TextBlock bttnText = App.FindFirstElementInVisualTree<TextBlock>(itemButton);
            VisualStateManager.GoToState(itemButton, "Normal", true);
            //   return bttnText.Text;
        }

        private String FocusCurrentItem()
        {
            Debug.WriteLine("Focus current index = " + CurrentIndex);
            ListBoxItem item = ContentPanel.ItemContainerGenerator.ContainerFromIndex(CurrentIndex) as ListBoxItem;
            Button itemButton = App.FindFirstElementInVisualTree<Button>(item);
            Debug.WriteLine("Focus current index = " + CurrentIndex + " " + (itemButton == null));
            TextBlock bttnText = App.FindFirstElementInVisualTree<TextBlock>(itemButton);
            VisualStateManager.GoToState(itemButton, "MouseOver", true);
            return bttnText.Text;
        }

        private String GetNextFeedName()
        {
            int nextIndx = (CurrentIndex + 1) % SubscribedFeedSources.Count;
            Debug.WriteLine("nextIndx = " + nextIndx);
            ListBoxItem item = ContentPanel.ItemContainerGenerator.ContainerFromIndex(nextIndx) as ListBoxItem;
            Button itemButton = App.FindFirstElementInVisualTree<Button>(item);
            TextBlock bttnText = App.FindFirstElementInVisualTree<TextBlock>(itemButton);
            return bttnText.Text;
        }

        private String GetPreviousFeedName()
        {
            int nextIndx = (CurrentIndex - 1 + SubscribedFeedSources.Count) % SubscribedFeedSources.Count;
            Debug.WriteLine("previousIndx = " + nextIndx);
            ListBoxItem item = ContentPanel.ItemContainerGenerator.ContainerFromIndex(nextIndx) as ListBoxItem;
            Button itemButton = App.FindFirstElementInVisualTree<Button>(item);
            TextBlock bttnText = App.FindFirstElementInVisualTree<TextBlock>(itemButton);
            return bttnText.Text;
        }

        private void UnsubscribeClick(object sender, RoutedEventArgs e)
        {
            MenuItem b = sender as MenuItem;
            FeedSource src = b.DataContext as FeedSource;
            SubscribedFeedSources.Remove(src);
            FeedSource fs = MainPage.MainModel.FeedSources.Single<FeedSource>(f => f.SourceId == src.SourceId);
            fs.IsSubscribed = false;
            MainPage.MainModel.SubmitChanges();
        }


        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
}